package services

import (
	"context"
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"google.golang.org/grpc"
	"log"
	"userauthserver/codeserver"
	userauth "userauthserver/proto"
)

type AuthServicesA struct {}

type User struct {
	Id int
	Name string
	Password string
	Al string
	UId string
}

func usemysql () (*gorm.DB , error) {
	return gorm.Open("mysql" , "root:123456@/oauth?charset=utf8&parseTime=True&loc=Local")
}

func getcode (userid string) string {
	con , err := grpc.Dial(":8081" , grpc.WithInsecure())
	if err != nil {
		log.Println(err , errors.New("get code default"))
	}
	client := codeserver.NewCodeServerClient(con)
	rep , err := client.GetCode(context.Background() , &codeserver.GetCodeReuqest{UserId: userid})
	if err != nil || rep == nil{
		log.Println(err)
		return ""
	}
	return rep.Code
}

func (a AuthServicesA) AuthT(ctx context.Context, req *userauth.AuthRequest) (*userauth.AuthResponse, error) {
	con , err := usemysql()
	if err != nil {
		log.Println(err)
		return nil , errors.New("the database is connect default")
	}
	var u User
	con.Table("user").Where("uid =?" , req.Id).Find(&u)
	fmt.Println(u)
	if &u == nil {
		return nil , errors.New("the id is wrong ")
	}
	fmt.Println(req.Password , u.Password)
	if req.Password != u.Password {
		return nil , errors.New("the user password is wrong")
	}
	code :=getcode(req.Id)
	if code == "" {
		return &userauth.AuthResponse{IsTrue: false} , nil
	}
	return &userauth.AuthResponse{Code: code , IsTrue: true} , nil
}